﻿using System;
using System.Linq;
using System.Web;
using System.IO;

using IdeaNMR.Web.Core;

namespace IdeaNMR.Web
{
    public partial class GetMacro : System.Web.UI.Page
    {
        // ALISTAIR: comment added 12/07/2011
        // The entire loading of the macro is performed in the Page_Load
        // method of the ASP.NET lifecycle
        protected void Page_Load(object sender, EventArgs e)
        {
            bool isFileNotFound = false;
            Guid TargetID;

            string CurrentScript = null;
            string CurrentName = null;

            if (Request["ExperimentID"] != null)
            {
                try
                {
                    // create a GUID based on the request parameter holding the ExperimentID
                    TargetID = new Guid(Request["ExperimentID"]);

                    //Accessing Database to get the Content and Name of Setup with id = SetupID and Username = SessionFacade.Username
                    //The Content is placed into string CurrentContent and Name into CurrentName
                    //Requested SetupID must belong to Username (validated in query)
                    #region Get Content from DB into CurrentContent and Name into CurrentName

                    // Establish a new database connection
                    using (IdeaNMRdbContainer inmr = new IdeaNMRdbContainer())
                    {
                        // Execute SQL query to get the experiment that matches the selected experiment.
                        // Also ensure that the current user is the owner of the experiment
                        // (access the User table from the experiment then get the Username, g.User.Username).
                        // Select the macro script and experiment name of the first result (there should only be one).
                        var exp = (from g in inmr.Experiments
                                   where g.Id == TargetID && g.User.Username == ScrewTurnWikiFacade.Username
                                   select new
                                   {
                                       Script = g.Script,
                                       Name = g.Name
                                   }).FirstOrDefault();

                        // copy the script and name to local variables
                        CurrentScript = exp.Script;
                        CurrentName = exp.Name;
                    }

                    if (CurrentName == string.Empty || CurrentName == null || CurrentScript == string.Empty || CurrentScript == null)
                    {
                        ScrewTurn.Wiki.Log.LogEntry("The search for Setup returned no result.", ScrewTurn.Wiki.PluginFramework.EntryType.Warning, ScrewTurnWikiFacade.Username);
                        Response.StatusCode = 404;
                        Response.Write(ScrewTurn.Wiki.Properties.Messages.FileNotFound);
                        return;
                    }

                    #endregion
                }
                catch (Exception) { isFileNotFound = true; }
            }
            else
            {
                try
                {
                    CurrentScript = Session["ReadyScript"].ToString();
                    CurrentName = Session["ReadyName"].ToString();

                    if (CurrentName == null || CurrentScript == null) isFileNotFound = true;
                    else
                    {
                        Session.Remove("ReadyScript");
                        Session.Remove("ReadyName");
                    }
                }
                catch { isFileNotFound = true; }
            }
            if (isFileNotFound)
            {
                Response.StatusCode = 404;
                Response.Write(ScrewTurn.Wiki.Properties.Messages.FileNotFound);
                return;
            }

            //Create Temporary file (Path - Settings.TempDirectory, Name - GetTempFileName)
            //string TempFile - is to download to client
            //#region Create Temp File for Download
            //string TempFileName = Path.GetFileName(Path.GetTempFileName());
            //string TempFile = Settings.TempDirectory + TempFileName;
            //FileStream fs = File.OpenWrite(TempFile);
            //StreamWriter sw = new StreamWriter(fs);

            //sw.Write(CurrentScript);
            //sw.Close();
            //fs.Close();
            //#endregion

            string mime = "application/octet-stream";

            //Form the Response to send Temporary File under the Name CurrentName.mac
            //Then delete temp file
            #region
            Response.Clear();
            Response.AddHeader("content-type", mime);
            // specify that the response consists of a file attachment, using the current filename
            Response.AddHeader("content-disposition", "attachment;filename=\"" + CurrentName + "\"");

            // Set the cache duration accordingly to the file date/time
         //   Response.AddFileDependency(TempFile);
         //   Response.Cache.SetETagFromFileDependencies();
         //   Response.Cache.SetLastModifiedFromFileDependencies();
            Response.Cache.SetCacheability(HttpCacheability.Public);
            Response.Cache.SetSlidingExpiration(true);
            Response.Cache.SetValidUntilExpires(true);
            Response.Cache.VaryByParams["File"] = true;
            
            // write the script to the resp
            Response.Write(CurrentScript);

          //  Response.WriteFile(TempFile);
            Response.Flush();
            Response.Close();
            #endregion
         //   File.Delete(TempFile);
        } // end Page_Load

    } // end GetMacro partial class
}